<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Services\TaxService;
use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class InvoiceController extends Controller
{
    protected $taxService;
    protected $smsService;

    public function __construct(TaxService $taxService, SmsService $smsService)
    {
        $this->taxService = $taxService;
        $this->smsService = $smsService;
    }

    /**
     * 获取开票记录列表
     */
    public function index(Request $request)
    {
        $query = Invoice::with(['tenant', 'appliedBy', 'processedBy'])
            ->where('tenant_id', Auth::user()->tenant_id);

        // 搜索过滤
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('invoice_application_no', 'like', "%{$search}%")
                  ->orWhere('invoice_title', 'like', "%{$search}%")
                  ->orWhere('invoice_number', 'like', "%{$search}%")
                  ->orWhere('invoice_content', 'like', "%{$search}%");
            });
        }

        // 发票类型过滤
        if ($request->filled('invoice_type')) {
            $query->where('invoice_type', $request->invoice_type);
        }

        // 状态过滤
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // 金额范围过滤
        if ($request->filled('min_amount')) {
            $query->where('amount', '>=', $request->min_amount);
        }
        if ($request->filled('max_amount')) {
            $query->where('amount', '<=', $request->max_amount);
        }

        // 申请时间范围过滤
        if ($request->filled('start_date')) {
            $query->whereDate('application_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('application_date', '<=', $request->end_date);
        }

        // 排序
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        $invoices = $query->paginate($request->get('per_page', 15));

        return response()->json([
            'success' => true,
            'data' => $invoices
        ]);
    }

    /**
     * 获取开票记录详情
     */
    public function show($id)
    {
        $invoice = Invoice::with(['tenant', 'appliedBy', 'processedBy'])
            ->where('tenant_id', Auth::user()->tenant_id)
            ->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $invoice
        ]);
    }

    /**
     * 创建开票申请
     */
    public function store(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:0',
            'invoice_type' => ['required', Rule::in(['ordinary', 'special', 'electronic'])],
            'invoice_title' => 'required|string|max:200',
            'tax_number' => 'nullable|string|max:50',
            'company_address' => 'nullable|string|max:200',
            'company_phone' => 'nullable|string|max:50',
            'bank_name' => 'nullable|string|max:100',
            'bank_account' => 'nullable|string|max:50',
            'invoice_content' => 'required|string|max:500',
        ]);

        // 专用发票需要完整的企业信息
        if ($request->invoice_type === 'special') {
            $request->validate([
                'tax_number' => 'required|string|max:50',
                'company_address' => 'required|string|max:200',
                'company_phone' => 'required|string|max:50',
                'bank_name' => 'required|string|max:100',
                'bank_account' => 'required|string|max:50',
            ]);
        }

        DB::beginTransaction();
        try {
            $invoice = Invoice::create([
                'invoice_application_no' => Invoice::generateApplicationNo(),
                'tenant_id' => Auth::user()->tenant_id,
                'amount' => $request->amount,
                'invoice_type' => $request->invoice_type,
                'invoice_title' => $request->invoice_title,
                'tax_number' => $request->tax_number,
                'company_address' => $request->company_address,
                'company_phone' => $request->company_phone,
                'bank_name' => $request->bank_name,
                'bank_account' => $request->bank_account,
                'invoice_content' => $request->invoice_content,
                'status' => 'pending',
                'application_date' => now(),
                'applied_by' => Auth::id(),
            ]);

            DB::commit();

            // 发送申请通知短信
            try {
                $this->smsService->sendInvoiceApplicationNotification(
                    Auth::user()->phone ?? '',
                    $invoice->invoice_application_no
                );
            } catch (\Exception $e) {
                Log::warning('发送开票申请通知短信失败: ' . $e->getMessage());
            }

            return response()->json([
                'success' => true,
                'message' => '开票申请提交成功',
                'data' => $invoice->load(['tenant', 'appliedBy'])
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('创建开票申请失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '创建开票申请失败'
            ], 500);
        }
    }

    /**
     * 更新开票申请
     */
    public function update($id, Request $request)
    {
        $invoice = Invoice::where('tenant_id', Auth::user()->tenant_id)
                         ->where('status', 'pending')
                         ->findOrFail($id);

        $request->validate([
            'amount' => 'sometimes|required|numeric|min:0',
            'invoice_type' => ['sometimes', 'required', Rule::in(['ordinary', 'special', 'electronic'])],
            'invoice_title' => 'sometimes|required|string|max:200',
            'tax_number' => 'nullable|string|max:50',
            'company_address' => 'nullable|string|max:200',
            'company_phone' => 'nullable|string|max:50',
            'bank_name' => 'nullable|string|max:100',
            'bank_account' => 'nullable|string|max:50',
            'invoice_content' => 'sometimes|required|string|max:500',
        ]);

        // 专用发票需要完整的企业信息
        if ($request->filled('invoice_type') && $request->invoice_type === 'special') {
            $request->validate([
                'tax_number' => 'required|string|max:50',
                'company_address' => 'required|string|max:200',
                'company_phone' => 'required|string|max:50',
                'bank_name' => 'required|string|max:100',
                'bank_account' => 'required|string|max:50',
            ]);
        }

        try {
            $invoice->update($request->only([
                'amount', 'invoice_type', 'invoice_title', 'tax_number',
                'company_address', 'company_phone', 'bank_name', 'bank_account',
                'invoice_content'
            ]));

            return response()->json([
                'success' => true,
                'message' => '开票申请更新成功',
                'data' => $invoice->fresh(['tenant', 'appliedBy', 'processedBy'])
            ]);

        } catch (\Exception $e) {
            Log::error('更新开票申请失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '更新开票申请失败'
            ], 500);
        }
    }

    /**
     * 审核开票申请
     */
    public function approve($id, Request $request)
    {
        $request->validate([
            'action' => ['required', Rule::in(['approve', 'reject'])],
            'reject_reason' => 'required_if:action,reject|string|max:500',
        ]);

        $invoice = Invoice::where('tenant_id', Auth::user()->tenant_id)
                         ->where('status', 'pending')
                         ->findOrFail($id);

        DB::beginTransaction();
        try {
            if ($request->action === 'approve') {
                // 税务系统验证
                $taxResult = $this->taxService->validateInvoiceInfo([
                    'invoice_title' => $invoice->invoice_title,
                    'tax_number' => $invoice->tax_number,
                    'amount' => $invoice->amount,
                    'invoice_type' => $invoice->invoice_type
                ]);

                if (!$taxResult['success']) {
                    throw new \Exception('税务验证失败: ' . $taxResult['message']);
                }

                $invoice->approve(Auth::id());
                $message = '开票申请已审核通过';
            } else {
                $invoice->reject($request->reject_reason, Auth::id());
                $message = '开票申请已拒绝';
            }

            DB::commit();

            // 发送审核结果通知短信
            try {
                $this->smsService->sendInvoiceApprovalNotification(
                    $invoice->appliedBy->phone ?? '',
                    $invoice->invoice_application_no,
                    $request->action === 'approve'
                );
            } catch (\Exception $e) {
                Log::warning('发送审核结果通知短信失败: ' . $e->getMessage());
            }

            return response()->json([
                'success' => true,
                'message' => $message,
                'data' => $invoice->fresh(['tenant', 'appliedBy', 'processedBy'])
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('审核开票申请失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '审核失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 完成开票
     */
    public function complete($id, Request $request)
    {
        $request->validate([
            'invoice_number' => 'required|string|max:50',
        ]);

        $invoice = Invoice::where('tenant_id', Auth::user()->tenant_id)
                         ->where('status', 'approved')
                         ->findOrFail($id);

        DB::beginTransaction();
        try {
            // 调用税务系统开票
            $invoiceResult = $this->taxService->issueInvoice([
                'invoice_title' => $invoice->invoice_title,
                'tax_number' => $invoice->tax_number,
                'amount' => $invoice->amount,
                'invoice_type' => $invoice->invoice_type,
                'invoice_content' => $invoice->invoice_content,
                'invoice_number' => $request->invoice_number
            ]);

            if (!$invoiceResult['success']) {
                throw new \Exception('税务系统开票失败: ' . $invoiceResult['message']);
            }

            $invoice->complete($request->invoice_number);

            DB::commit();

            // 发送开票完成通知短信
            try {
                $this->smsService->sendInvoiceCompletionNotification(
                    $invoice->appliedBy->phone ?? '',
                    $invoice->invoice_application_no,
                    $request->invoice_number
                );
            } catch (\Exception $e) {
                Log::warning('发送开票完成通知短信失败: ' . $e->getMessage());
            }

            return response()->json([
                'success' => true,
                'message' => '开票完成',
                'data' => $invoice->fresh(['tenant', 'appliedBy', 'processedBy'])
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('完成开票失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '开票失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 取消开票申请
     */
    public function cancel($id)
    {
        $invoice = Invoice::where('tenant_id', Auth::user()->tenant_id)
                         ->whereIn('status', ['pending', 'approved'])
                         ->findOrFail($id);

        try {
            $invoice->update([
                'status' => 'cancelled'
            ]);

            return response()->json([
                'success' => true,
                'message' => '开票申请已取消',
                'data' => $invoice->fresh(['tenant', 'appliedBy', 'processedBy'])
            ]);

        } catch (\Exception $e) {
            Log::error('取消开票申请失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '取消开票申请失败'
            ], 500);
        }
    }

    /**
     * 获取开票统计数据
     */
    public function statistics(Request $request)
    {
        $tenantId = Auth::user()->tenant_id;
        
        // 时间范围
        $startDate = $request->get('start_date', now()->startOfMonth());
        $endDate = $request->get('end_date', now()->endOfMonth());

        $query = Invoice::where('tenant_id', $tenantId)
                       ->whereBetween('application_date', [$startDate, $endDate]);

        // 总体统计
        $totalStats = [
            'total_count' => $query->count(),
            'total_amount' => $query->sum('amount'),
            'pending_count' => $query->where('status', 'pending')->count(),
            'pending_amount' => $query->where('status', 'pending')->sum('amount'),
            'approved_count' => $query->where('status', 'approved')->count(),
            'approved_amount' => $query->where('status', 'approved')->sum('amount'),
            'invoiced_count' => $query->where('status', 'invoiced')->count(),
            'invoiced_amount' => $query->where('status', 'invoiced')->sum('amount'),
            'rejected_count' => $query->where('status', 'rejected')->count(),
            'rejected_amount' => $query->where('status', 'rejected')->sum('amount'),
        ];

        // 按类型统计
        $typeStats = Invoice::where('tenant_id', $tenantId)
                           ->whereBetween('application_date', [$startDate, $endDate])
                           ->selectRaw('invoice_type, COUNT(*) as count, SUM(amount) as total_amount')
                           ->groupBy('invoice_type')
                           ->get();

        // 按状态统计
        $statusStats = Invoice::where('tenant_id', $tenantId)
                             ->whereBetween('application_date', [$startDate, $endDate])
                             ->selectRaw('status, COUNT(*) as count, SUM(amount) as total_amount')
                             ->groupBy('status')
                             ->get();

        // 按日期统计（最近30天）
        $dailyStats = Invoice::where('tenant_id', $tenantId)
                            ->whereBetween('application_date', [now()->subDays(30), now()])
                            ->selectRaw('DATE(application_date) as date, COUNT(*) as count, SUM(amount) as total_amount')
                            ->groupBy('date')
                            ->orderBy('date')
                            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'total_stats' => $totalStats,
                'type_stats' => $typeStats,
                'status_stats' => $statusStats,
                'daily_stats' => $dailyStats
            ]
        ]);
    }

    /**
     * 批量处理开票申请
     */
    public function batchProcess(Request $request)
    {
        $request->validate([
            'invoice_ids' => 'required|array|min:1',
            'invoice_ids.*' => 'exists:invoices,id',
            'action' => ['required', Rule::in(['approve', 'reject'])],
            'reject_reason' => 'required_if:action,reject|string|max:500',
        ]);

        $invoices = Invoice::where('tenant_id', Auth::user()->tenant_id)
                          ->where('status', 'pending')
                          ->whereIn('id', $request->invoice_ids)
                          ->get();

        if ($invoices->count() !== count($request->invoice_ids)) {
            return response()->json([
                'success' => false,
                'message' => '部分开票申请不存在或状态不正确'
            ], 400);
        }

        DB::beginTransaction();
        try {
            $results = [];
            
            foreach ($invoices as $invoice) {
                if ($request->action === 'approve') {
                    $invoice->approve(Auth::id());
                } else {
                    $invoice->reject($request->reject_reason, Auth::id());
                }
                
                $results[] = $invoice->fresh();
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '批量处理完成',
                'data' => $results
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('批量处理开票申请失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '批量处理失败'
            ], 500);
        }
    }

    /**
     * 导出开票记录
     */
    public function export(Request $request)
    {
        $query = Invoice::with(['tenant', 'appliedBy', 'processedBy'])
            ->where('tenant_id', Auth::user()->tenant_id);

        // 应用过滤条件
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('invoice_type')) {
            $query->where('invoice_type', $request->invoice_type);
        }
        if ($request->filled('start_date')) {
            $query->whereDate('application_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('application_date', '<=', $request->end_date);
        }

        $invoices = $query->orderBy('application_date', 'desc')->get();

        // 构建导出数据
        $exportData = $invoices->map(function ($invoice) {
            return [
                '申请单号' => $invoice->invoice_application_no,
                '发票类型' => $invoice->type_display,
                '发票抬头' => $invoice->invoice_title,
                '税号' => $invoice->tax_number,
                '开票金额' => $invoice->amount,
                '开票内容' => $invoice->invoice_content,
                '状态' => $invoice->status_display,
                '发票号码' => $invoice->invoice_number,
                '申请时间' => $invoice->application_date?->format('Y-m-d'),
                '处理时间' => $invoice->processed_date?->format('Y-m-d'),
                '开票时间' => $invoice->invoice_date?->format('Y-m-d'),
                '申请人' => $invoice->appliedBy?->name,
                '处理人' => $invoice->processedBy?->name,
            ];
        });

        return response()->json([
            'success' => true,
            'data' => $exportData,
            'filename' => '开票记录_' . now()->format('Y-m-d_H-i-s') . '.xlsx'
        ]);
    }
}